#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Common.hpp"

#define Convert(addrptr) ((struct sockaddr *)addrptr)

namespace Net_Work
{

    enum
    {
        SocketError = 1,
        BindError,
        ListenError
    };
    const static int defaultsockfd = -1;
    const int backlog = 5;
    // 封装一个基类，Socket接口类
    class Socket
    {
    public:
        virtual ~Socket() {}
        virtual void CreateSocketOrDie() = 0;
        virtual void BindSocketOrDie(uint16_t port) = 0;
        virtual void ListenSocketOrDie(int backlog) = 0;
        virtual int AcceptConnection(std::string *peerip, uint16_t *peerport) = 0; // 返回文件描述符以及客户端的信息(参数为输出型参数)
        virtual bool ConnectServer(const std::string &serverip, uint16_t serverport) = 0;
        virtual int GetSockFd() = 0;
        virtual void SetSockFd(int sockfd) = 0;
        virtual void CloseSockFd() = 0;
        virtual bool Recv(std::string *buffer, int size) = 0;
        virtual void Send(std::string &send_str) = 0;

    public:
        void BuildListenSocketMethod(uint16_t port, int backlog)
        {
            // bind监听（服务端） ip地址不需要设置为固定的ip，只需指定端口即可（传端口号）
            CreateSocketOrDie();

            BindSocketOrDie(port);
            ListenSocketOrDie(backlog);
        }

        bool BuildConnectSocketMethod(const std::string &serverip, uint16_t serverport)
        {
            // 客户端连接时需要服务端的ip地址和端口号
            CreateSocketOrDie();
            return ConnectServer(serverip, serverport);
        }
        void BuildNormalSocketMethod(int sockfd)
        {
            SetSockFd(sockfd);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = defaultsockfd)
            : _sockfd(sockfd)
        {
        }
        ~TcpSocket()
        {
        }
        // override: 检查派生类虚函数是否重写了基类某个虚函数，如果没有重写编译报错
        void CreateSocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0); // 创建套接字

            if (_sockfd < 0)
                exit(SocketError);
            SetNonBlock(_sockfd);
        }
        void BindSocketOrDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = INADDR_ANY;
            local.sin_port = htons(port);
            int n = ::bind(_sockfd, Convert(&local), sizeof(local));
            if (n < 0)
                exit(BindError);
        }
        void ListenSocketOrDie(int backlog) override
        {
            // backlog：内核允许在等待连接队列中排队的最大连接数
            int n = ::listen(_sockfd, backlog);
            if (n < 0)
                exit(ListenError);
        }

        int AcceptConnection(std::string *peerip, uint16_t *peerport) override
        // 返回文件描述符以及客户端的信息(参数为输出型参数)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsockfd = accept(_sockfd, Convert(&peer), &len);
            if (newsockfd < 0)
                return -1;
            *peerport = ntohs(peer.sin_port);
            *peerip = inet_ntoa(peer.sin_addr);
            return newsockfd;
        }

        bool ConnectServer(const std::string &serverip, uint16_t serverport) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(serverip.c_str());
            server.sin_port = htons(serverport);
            socklen_t len = sizeof(server);
            int n = ::connect(_sockfd, Convert(&server), len);

            // std::cout << errno << strerror(errno) << std::endl;
            if (n == 0)
                return true;
            else
                return false;
        }

        int GetSockFd() override
        {
            return _sockfd;
        }
        void SetSockFd(int sockfd) override
        {
            _sockfd = sockfd;
        }
        void CloseSockFd() override
        {
            if (_sockfd > defaultsockfd)
                close(_sockfd);
        }
        bool Recv(std::string *buffer, int size) override
        {
            char inbuffer[size];
            ssize_t n = recv(_sockfd, inbuffer, size - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                *buffer += inbuffer; // 这里读取时是+=不会覆盖原有剩余的报文
                return true;
            }
            // else if(n < 0 || n == 0) return false;
            return false;
        }
        void Send(std::string &send_str) override
        {
            send(_sockfd, send_str.c_str(), send_str.size(), 0);
        }

    private:
        int _sockfd;
    };
}
